#######################################################################################################################
import sys
import os
import json
import glob
import misp


#######################################################################################################################
indir_name = 'input'
tempdir_name = 'temp'
outdir_name = 'output'
tile_txt_mask = os.path.join(tempdir_name,'tile*.txt')
misptemp_name = 'misptemp'
mispfile_name = 'mispfile'


#######################################################################################################################
# read command line
params = json.loads(sys.argv[1])
current_phase = params['current_phase']

# init misp data
misp = misp.misp_t()
misp.set_option('multi_pass_gen', True)

# configs
misp.add_config(id='clean')
misp.add_config(id='map')
misp.add_config(id='all')

# phases
misp.add_phase(id='clean_all',configs=['clean'])
misp.add_phase(id='create_dirs',configs=['map','all'])
misp.add_phase(id='convert_map',configs=['map','all'])
misp.add_phase(id='convert_tiles',configs=['all'])
misp.set_current_phase(current_phase)

# clean all
if current_phase == 'clean_all':
	misp.add_formula(id = 'clean', 
							actions = [
								# next line is commented out intentionally
								#['-s', 'del %s' % mispfile_name],
								['-s', 'rd /s /q %s' % tempdir_name],
								['-s', 'rd /s /q %s' % outdir_name],
								])

# output dir
elif current_phase == 'create_dirs':
	misp.add_formula(id = tempdir_name,
						targets = [tempdir_name],
						actions= [
							['-s', 'md %s' % tempdir_name],
							])
	misp.add_formula(id = outdir_name,
						targets = [outdir_name],
						actions= [
							['-s', 'md %s' % outdir_name],
							])

# convert map
elif current_phase == 'convert_map':
	level_raw_name = os.path.join(indir_name,'level.raw')
	level_data_name = os.path.join(outdir_name,'level.dat')
	tile_mask = os.path.join(tempdir_name,'tile_%03d.txt')
	misp.add_formula(id = level_data_name,
						sources = [level_raw_name, 'tools\\conv_level.py'],
						targets = [level_data_name],
						actions = [
							['-s', 'del %s' % tile_txt_mask],
							['','python tools\\conv_level.py %s %s %s' % (level_raw_name, level_data_name, tile_mask)],
							])

# convert tiles
elif current_phase == 'convert_tiles':
	tile_raw_names = glob.glob(tile_txt_mask)
	for tile_raw_name in tile_raw_names:
		name_ext = os.path.split(tile_raw_name)[1]
		name = os.path.splitext(name_ext)[0]
		tile_data_name = os.path.join(outdir_name,name+'.dat')
		misp.add_formula(id = tile_data_name,
							sources = [tile_raw_name, 'tools\\conv_tile.py'],
							targets = [tile_data_name],
							actions = [
								['','python tools\\conv_tile.py %s %s' % (tile_raw_name, tile_data_name)],
								])

# save
misp.write_misptemp(misptemp_name)
